#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QImage"
#include "QPainter"
#include "QDebug"
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //open carema
    cap.open(0);//dev/video
    //start timer envent
    startTimer(100);
    //input jilian
    cascade.load("/opt/opencv4-pc/share/opencv4/haarcascades/haarcascade_frontalface_alt2.xml");
    //QTcpSocket send disconnect signal when  disconnet;send connected signal when connect with serivce successfully
    connect(&msocket,&QTcpSocket::disconnected,this,&MainWindow::start_connect);
    connect(&msocket,&QTcpSocket::connected,this,&MainWindow::stop_connect);
    // connect to service on time
    connect(&mtimer,&QTimer::timeout,this,&MainWindow::timer_connect);
    //start timer
    mtimer.start(5000);//each 5 mins to connect with service until connect successful
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::timerEvent(QTimerEvent *e)
{
    //collect data
    Mat srcImage;
    if(cap.grab())
    {
        cap.read(srcImage);//read a frame of data
    }
    //make a gray Image for improving the speed of detecting face
    Mat grayImage;
    //convert to grayImage
    cvtColor(srcImage,grayImage,COLOR_BGRA2GRAY);
    //detect face data;
    std::vector<Rect>faceRects;
    cascade.detectMultiScale(srcImage,faceRects);
    if(faceRects.size()>0)
    {
        Rect  rect=faceRects.at(0);
//        rectangle(srcImage,rect,Scalar(0,255,255));
        //move face tangulation
        ui->headerpic->move(rect.x,rect.y);
        //Mat data is convert QbyteArray,in a world ,encoding jpg form
        std::vector<uchar>buff;
        cv::imencode(".jpg",srcImage,buff);
        QByteArray byte((const char *)buff.data(),buff.size());
        //ready to send
        quint64 backsize=byte.size();
        QByteArray sendData;
        QDataStream stream(&sendData,QIODevice::WriteOnly);
        stream.setVersion(QDataStream::Qt_5_14);
        stream<<backsize<<byte;
        //send
        msocket.write(sendData);
    }
    else
    {
        // face tangulation is moved to the center of windows;
        ui->headerpic->move(100,60);
    }
    if (srcImage.data==nullptr)
        return;
    //Mat form of data(BGR) in opencv is converted to QImage form of data(RGB)
    cvtColor(srcImage,srcImage,COLOR_BGR2RGB);
    QImage  image(srcImage.data,srcImage.cols,srcImage.rows,srcImage.step1(),QImage::Format_RGB888);
    QPixmap mmp=QPixmap::fromImage(image);
    ui->videoLb->setPixmap(mmp);
}

void MainWindow::timer_connect()
{
    //connect server
    msocket.connectToHost("192.168.137.128",7777);
    qDebug()<<"connecting service";
}

void MainWindow::start_connect()
{
    mtimer.start(5000);//start timer
    qDebug()<<"disconnect";
}
void MainWindow::stop_connect()
{
    mtimer.stop();
    qDebug()<<"connect with service successfully";
}
